package com.op.teachingliteapp.database.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;

import com.op.teachingliteapp.bean.CourseBean;
import com.op.teachingliteapp.database.DBHelper;
import com.op.teachingliteapp.database.table.CourseTable;
import com.op.teachingliteapp.util.StringUtils;

/**
 * Created by Genji on 2015/6/24. Modified by Kevin
 */
public class CourseDao extends AbstractDao {
	public CourseDao(Context context, String userId) {
		super(context, userId);
		this.tb = CourseTable.TABLE_COURSE;
	}

	/**
	 * 通过用户id来获得该用户的所有课程
	 * 
	 * @param userId
	 * @return
	 */
	public List<CourseBean> getCoursesByUserId(String userId) {
		List<CourseBean> courseList = new ArrayList<CourseBean>();

		// String sql = "select * from course where userId = 123";

		Cursor cursor = db.query(this.tb, CourseTable.PROJECTION, CourseTable.COLUMN_USER_ID + "=" + StringUtils.wrapQuote(userId), null, null, null, null);
		while (cursor.moveToNext()) {
			courseList.add(this.makeCourseBeanByCursor(cursor));
		}

		return courseList;
	}

	/**
	 * 辅助类，用于生成实例
	 * 
	 * @param cursor
	 * @return
	 */
	private CourseBean makeCourseBeanByCursor(Cursor cursor) {
		CourseBean courseBean = new CourseBean();

		courseBean.setId(cursor.getString(cursor.getColumnIndex(CourseTable.COLUMN_ID)));
		courseBean.setCreateTime(cursor.getString(cursor.getColumnIndex(CourseTable.COLUMN_CREATE_TIME)));
		courseBean.setUpdateTime(cursor.getString(cursor.getColumnIndex(CourseTable.COLUMN_UPDATE_TIME)));
		courseBean.setName(cursor.getString(cursor.getColumnIndex(CourseTable.COLUMN_NAME)));
		courseBean.setCredit(cursor.getString(cursor.getColumnIndex(CourseTable.COLUMN_CREDIT)));
		courseBean.setPeriod(cursor.getString(cursor.getColumnIndex(CourseTable.COLUMN_PERIOD)));
		courseBean.setUserId(cursor.getString(cursor.getColumnIndex(CourseTable.COLUMN_USER_ID)));
		courseBean.setIconUrl(cursor.getString(cursor.getColumnIndex(CourseTable.COLUMN_ICON_URL)));
		courseBean.setDeptId(cursor.getString(cursor.getColumnIndex(CourseTable.COLUMN_DEPT_ID)));
		return courseBean;
	}
}
